package io.jnet.server.accepthandler.impl;

import java.io.IOException;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import io.jnet.common.api.ChannelContext;
import io.jnet.common.util.AioListener;
import io.jnet.server.accepthandler.AcceptHandler;
import io.jnet.server.build.ServerChannelContextBuilder;
import io.jnet.server.build.ServerChannelContextConfig;

public abstract class AbstractAcceptHandler implements AcceptHandler
{
    protected ServerChannelContextBuilder     channelContextBuilder;
    protected AsynchronousServerSocketChannel serverSocketChannel;
    protected AioListener                     serverListener;
    
    public AbstractAcceptHandler(AsynchronousServerSocketChannel serverSocketChannel, ServerChannelContextBuilder channelContextBuilder, AioListener serverListener)
    {
        this.channelContextBuilder = channelContextBuilder;
        this.serverSocketChannel = serverSocketChannel;
        this.serverListener = serverListener;
    }
    
    @Override
    public void completed(AsynchronousSocketChannel socketChannel, Object attachment)
    {
        ServerChannelContextConfig config = channelContextBuilder.onConnect(socketChannel);
        ChannelContext serverChannelContext = parse(socketChannel, config, serverListener);
        channelContextBuilder.afterContextBuild(serverChannelContext);
        serverChannelContext.registerRead();
        serverSocketChannel.accept(null, this);
    }
    
    protected abstract ChannelContext parse(AsynchronousSocketChannel socketChannel, ServerChannelContextConfig config, AioListener listener);
    
    @Override
    public void failed(Throwable exc, Object attachment)
    {
        try
        {
            serverSocketChannel.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
}
